/**
 * Copyright © 2011 looty - Textoo
 * @link http://www.textoo.org
 * @link http://code.google.com/p/textoo/
 * @author lab9 - Bertrand Larrieu
 * @mail lab9.fr@gmail.com
 * @version 2.0
 */

package org.looty.core.textoo.context.local 
{
	import flash.events.*;
	import flash.utils.*;
	import org.looty.log.*;
	import org.looty.textoo.events.*;
	
	public final class LocalisationManager extends EventDispatcher
	{
		private var _texts					:Dictionary;
		private var _index					:int;		
		private var _length					:uint;				
		
		static private const ADDED_EVENT	:TextooEvent = new TextooEvent(TextooEvent.LOCALISATION_ADDED);
		
		public function LocalisationManager() 
		{
			_texts = new Dictionary();
			_index = -1
		}		
		
		public function get index():int 
		{
			return _index;
		}
		
		public function set index(value:int):void 
		{
			_index = value;
			for (var key:String in _texts) LocalisationText(_texts[key]).index = value;
		}
		
		public function setLength(value:uint):void
		{
			_length = value;
			
			for (var key:String in _texts) LocalisationText(_texts[key]).setLength(value);
		}	
		
		public function addText(key:String, index:uint, text:String, className:String):void 
		{			
			var locText:LocalisationText = getText(key);
			text = text.replace(/(\r\n)|(\n\r)/g, "\n");
			if (locText != null) locText.populate(index, text, className);
		}
		
		public function setDefaultClass(key:String, className:String):void 
		{
			var locText:LocalisationText = getText(key);
			if (locText != null) locText.setDefaultClassName(className);
		}
		
		public function hasText(key:String):Boolean { return _texts[key] != undefined; }
		
		public function getText(key:String):LocalisationText 
		{
			if (key == null || key.length == 0)
			{
				Looger.error("key null or empty in org.looty.core.textoo.context.local.LocalisationManager");
				return null;
			}
			
			var locText:LocalisationText = _texts[key];
			
			if (locText == null)
			{
				locText = new LocalisationText(key, _length);
				_texts[key] = locText;
				
				dispatchEvent(ADDED_EVENT);
			}
			
			return _texts[key];
		}
		
		public function dispose():void
		{
			for each (var text:LocalisationText in _texts) 
			{
				text.dispose();
				_texts[text.key] = null;
				delete _texts[text.key];
			}
			
			_texts = null;
		}
		
		public function dump():void
		{
			Looger.info(" -- localisations --");
			for each (var text:LocalisationText in _texts) Looger.info(" " + text.dump());
		}		
		
		
		
		
		
	}

}